package com.yf.course.modules.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.base.api.api.dto.PagingReqDTO;
import com.yf.base.api.exception.ServiceException;
import com.yf.base.utils.BeanMapper;
import com.yf.course.modules.course.dto.CourseQaDTO;
import com.yf.course.modules.course.dto.request.CourseQaReqDTO;
import com.yf.course.modules.course.dto.response.CourseQaRespDTO;
import com.yf.course.modules.course.entity.CourseQa;
import com.yf.course.modules.course.mapper.CourseQaMapper;
import com.yf.course.modules.course.service.CourseQaService;

import com.yf.system.utils.HtmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
* <p>
* 课程问答业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2021-04-19 11:04
*/
@Service
public class CourseQaServiceImpl extends ServiceImpl<CourseQaMapper, CourseQa> implements CourseQaService {

    @Override
    public void save(CourseQaDTO reqDTO) {

        // 基本信息
        CourseQa entity = new CourseQa();
        BeanMapper.copy(reqDTO, entity);

        String content = entity.getContent();
        if(StringUtils.isBlank(content)){
            throw new ServiceException("提问内容不能为空");
        }

        // 自动获取title
        String title = HtmlUtils.splitAndFilterString(content, 30);
        entity.setTitle(title);

        // 管理回复
        if(!StringUtils.isBlank(reqDTO.getReplyId())){
            CourseQa reply = this.getById(reqDTO.getReplyId());
            entity.setCourseId(reply.getCourseId());
            entity.setFileId(reply.getFileId());
            reply.setState(1);
            this.updateById(reply);
        }

        this.saveOrUpdate(entity);
    }

    @Override
    public CourseQaRespDTO detail(String id) {
        CourseQaRespDTO respDTO = baseMapper.findDetail(id);
        return respDTO;
    }

    @Override
    public IPage<CourseQaRespDTO> paging(PagingReqDTO<CourseQaReqDTO> reqDTO) {
        //获得数据
        IPage<CourseQaRespDTO> pageData = baseMapper.paging(reqDTO.toPage(), reqDTO.getParams());
        return pageData;
     }

    /**
     * 查找某个问题的全部回答
     * @param id
     * @return
     */
     private List<CourseQaDTO> findReplies(String id){

         QueryWrapper<CourseQa> wrapper = new QueryWrapper<>();
         wrapper.lambda().eq(CourseQa::getReplyId, id);

         List<CourseQa> list = this.list(wrapper);
         List<CourseQaDTO> respDTO = new ArrayList<>();

         if(!CollectionUtils.isEmpty(list)){
             respDTO =BeanMapper.mapList(list, CourseQaDTO.class);
         }

         return respDTO;
     }
}
